from django.views.generic.list_detail import object_list 
from mailadmin.mailadmin.models import MailUser, MailAlias, MailDomain
from django.contrib.auth.decorators import login_required
from django import newforms as forms

def index(request):
    users = MailUser.objects.exclude(address="root@localhost")
    domains = MailDomain.objects.exclude(domain__startswith="localhost")
    aliases = MailAlias.objects.exclude(forwards_to__endswith="localhost").extra(where=["mail != destination"])
    
    d_message, d_submit_action, d_edit_id, domainform = build_form(request, MailDomain)
    al_message, al_submit_action, al_edit_id, aliasform = build_form(request, MailAlias)
    ac_message, ac_submit_action, ac_edit_id, accountform = build_form(request, MailUser)
    
    return limited_object_list(request, queryset=domains,
                       extra_context={
                       'users':users,
                       'forwarders':aliases,
                       'request':request,
                       'MailDomain_message':d_message,
                       'MailDomain_submit_action':d_submit_action,
                       'MailDomain_edit_id':d_edit_id,
                       'MailAlias_message':al_message,
                       'MailAlias_submit_action':al_submit_action,
                       'MailAlias_edit_id':al_edit_id,
                       'MailUser_message':ac_message,
                       'MailUser_submit_action':ac_submit_action,
                       'MailUser_edit_id':ac_edit_id,
                       'domainform':domainform.as_table(),
                       'accountform':accountform.as_table(),
                       'aliasform':aliasform.as_table(),
                       },
                       template_name="index.html", template_object_name="domain",)
@login_required
def limited_object_list(*args, **kwargs):
    return object_list(*args, **kwargs)

def build_form(request, model):
    message = ''
    submit_action = 'Add'
    edit_id = ''
    
    ModelForm = forms.form_for_model(model)
    modelform = ModelForm()
    
    if request.method == "GET":
        if request.has_key(model.__name__+"_edit_id"):
            modelinstance = model.objects.get(pk=request.GET[model.__name__+'_edit_id'])
            ModelForm = forms.form_for_instance(modelinstance)
            modelform = ModelForm()
            submit_action = 'Update'
            edit_id = request.GET[model.__name__+'_edit_id']
            message = 'Editing ' + ' ID ' + request.GET[model.__name__+'_edit_id']
        if request.has_key(model.__name__+'_delete_id'):
            model.objects.get(pk=request.GET[model.__name__+'_delete_id']).delete()
            message = 'deleted!'
        
    if request.method == "POST":
        if request.has_key(model.__name__+"_submit_action"):
            if request.POST[model.__name__+'_submit_action'] == 'Add':
              add_f = ModelForm(request.POST)
              if add_f.is_valid():
                add_f.save()
                message = ' added.'
              else:
                # validation failed: show submitted values in form
                modelform = add_f
            if request.POST[model.__name__+'_submit_action'] == 'Update':
              # attempt to do update
                item = model.objects.get(pk=request.POST[model.__name__+'_edit_id'])
                ModelForm = forms.form_for_instance(item)
                update_f = ModelForm(request.POST.copy())
                if update_f.is_valid():
                    update_f.save()
                    message = 'updated.'
                else:
                    # validation failed: prepare form for new update attempt
                    submit_action = 'Update'
                    edit_id = request.POST[model.__name__+'_edit_id']
                    modelform = update_f
    return message, submit_action, edit_id, modelform